package com.chat.ui.gallery;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chat.MyApplication;
import com.chat.R;
import com.chat.entity.DataPackage;
import com.chat.entity.Room;
import com.chat.entity.ServerAction;
import com.chat.entity.UserJoinRoomForm;
import com.chat.entity.event.ChannelEvent;
import com.chat.net.SocketClient;
import com.chat.net.socket.Channel;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

//聊天室搜索页面
public class GalleryFragment extends Fragment {

    private GalleryViewModel galleryViewModel;
    private RecyclerView recyclerView;
    private GalleryFragment.MyRecycleViewAdapter adapter;
    private List<HashMap<String,Object>> mData=new ArrayList<HashMap<String,Object>>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        galleryViewModel =
                ViewModelProviders.of(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_gallery, container, false);
        getData();
        recyclerView = root.findViewById(R.id.room_show_lists);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//垂直线性布局
        adapter = new MyRecycleViewAdapter();
        recyclerView.setAdapter(adapter);

        return root;
    }

    public void getData(){
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                adapter.notifyDataSetChanged();
            }
        };
        DataPackage request = DataPackage.request(ServerAction.GET_ROOMS);
//        ChatObjectServer.getServer().addObject(request);

        SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
            @Override
            public void onChannelEvent(Channel ctx, DataPackage source) {
                //处理聊天室信息
                if(source.getCode()==200){
                    List<Room>rooms = (List<Room>) source.getDate();
                    for(Room room:rooms){
                        HashMap<String,Object> item = new HashMap<>();
                        item.put("name",room.getName());
                        item.put("picture",R.drawable.dog);
                        item.put("id",room.getRoomId());
                        mData.add(item);
                    }
                    handler.sendMessage(Message.obtain());
                }
            }
        },request);

    }

    //自定义Adapter
    class  MyRecycleViewAdapter extends RecyclerView.Adapter<GalleryFragment.MyRecycleViewAdapter.ViewHolder>
    {


        public  class ViewHolder extends RecyclerView.ViewHolder {
            public ImageView picture;
            public TextView name;
            public ImageButton button;

            public ViewHolder(View convertView) {
                super(convertView);
                picture = (ImageView)convertView.findViewById(R.id.item_room_head);
                button = (ImageButton) convertView.findViewById(R.id.item_room_btn);
                name = (TextView)convertView.findViewById(R.id.item_room_name);
            }
        }
        @NonNull
        @Override
        public GalleryFragment.MyRecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v= LayoutInflater.from(getActivity()).inflate(R.layout.item_search_room,parent, false);
            return new GalleryFragment.MyRecycleViewAdapter.ViewHolder(v);
        }

        @Override
        public void onBindViewHolder(@NonNull GalleryFragment.MyRecycleViewAdapter.ViewHolder holder, final int position) {
            //picture
            final Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if(msg.what==200) {
                        Toast.makeText(getActivity(), "请求成功!"+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    }
                    else
                        Toast.makeText(getActivity(), "请求失败!"+msg.obj.toString(), Toast.LENGTH_SHORT).show();
                }
            };

            Glide.with(getActivity()).load(new MyApplication().imagebaseurl+mData.get(position).get("picture").toString()).placeholder(R.drawable.dog).into(holder.picture);
            holder.name.setText((String)mData.get(position).get("name"));
            holder.button.setBackgroundResource(R.drawable.add);
            holder.button.setOnClickListener(new View.OnClickListener() {//点击事件
                @Override
                public void onClick(View v) {
                    //发送请求
                    SharedPreferences sharedPreferences = getContext().getSharedPreferences("chat", Context.MODE_PRIVATE);
                    UserJoinRoomForm userJoinRoomForm = new UserJoinRoomForm();
                    userJoinRoomForm.setUserId(sharedPreferences.getInt("userId",-1));
                    userJoinRoomForm.setRoomId((Integer) mData.get(position).get("id"));
                    userJoinRoomForm.setCreateTime(new Date(Calendar.getInstance().getTimeInMillis()));

                    SocketClient.getSocketClient().addChannelEvent(new ChannelEvent() {
                        @Override
                        public synchronized void onChannelEvent(Channel ctx, DataPackage source) {
                            Message message = Message.obtain();
                            message.what = source.getCode();
                            message.obj = source.getDate();
                            handler.sendMessage(message);
                        }
                    },DataPackage.request(userJoinRoomForm,ServerAction.POST_ROOM_JOIN));
                }
            });
//            holder.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    NavController navController= Navigation.findNavController(getActivity(),R.id.nav_host_fragment);
//                    Bundle bundle=new Bundle();
//                    bundle.putInt("id",(int)mData.get(position).get("id"));
//                    navController.navigate(R.id.detailFragment,bundle);
//
//                }
//            });
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }
}
